# 历史对比模块
import os

import matplotlib.pyplot as plt
import cartopy.crs as crs
import numpy as np
from cartopy.io.shapereader import Reader
from matplotlib import ticker
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import shapefile
from matplotlib.axes import Axes
from matplotlib.contour import ContourSet
from matplotlib.patches import PathPatch
from matplotlib.path import Path
from cartopy import feature
from utils.rainDraw import cmap, norm, bounds


def clip_boundary(cs: ContourSet, axes: Axes, shape_file: str):
    """
    :param cs:            画图函数的返回值
    :param axes:          坐标系
    :param shape_file:    shape 文件地址
    裁剪 shape 文件外部的内容
    """
    shp = shapefile.Reader(shape_file)
    vertices = []
    codes = []
    for shape_rec in shp.shapeRecords():
        points = shape_rec.shape.points
        prt = list(shape_rec.shape.parts) + [len(points)]
        for i in range(len(prt) - 1):
            for j in range(prt[i], prt[i + 1]):
                vertices.append((points[j][0], points[j][1]))
            codes += [Path.MOVETO]
            codes += [Path.LINETO] * (prt[i + 1] - prt[i] - 2)
            codes += [Path.CLOSEPOLY]

    clip = Path(vertices, codes)
    clip = PathPatch(clip, transform=axes.transData)

    for contour in cs.collections:
        contour.set_clip_path(clip)


# 可视化降雨预测结果  展示到石家庄区县地图
def plot_rain_with_map(rain, title, fname=None, format="png"):
    # plt.clf()
    shape_file = "/Users/luofan/PyCharm/ShijiaZhuang/utils/shapeFile/石家庄市.shp"
    proj = crs.PlateCarree()  # 简写投影
    extent = [113.45, 115.54, 37.4, 38.8]  # 地图绘制范围
    scope = [113.5, 115.5, 37.0, 39.0]  # 数据范围
    # 分辨率
    resolution = 0.005
    # 设置中文字体
    plt.rcParams['font.family'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['font.serif'] = ['SimHei']
    # 设置背景颜色
    # 全局设置背景为白色
    plt.rcParams['figure.facecolor'] = 'white'
    plt.rcParams['axes.facecolor'] = 'white'
    plt.rcParams['savefig.facecolor'] = 'white'  # 保存图片时的背景色

    longitude_min, longitude_max, latitude_min, latitude_max = scope
    range_longitude = int((longitude_max - longitude_min) / resolution + 0.5)
    range_latitude = int((latitude_max - latitude_min) / resolution + 0.5)
    lon = np.linspace(longitude_min, longitude_max - resolution, range_longitude)
    lat = np.linspace(latitude_max - resolution, latitude_min, range_latitude)

    x, y = np.meshgrid(lon, lat)
    # 过滤降雨小于0.1的
    mask = rain <= 0.1
    rain = np.ma.array(rain, mask=mask)
    fig = plt.figure(dpi=900)
    fig.patch.set_facecolor('white')  # 图形背景

    axes = fig.subplots(1, 1, subplot_kw={'projection': proj})  # 创建子图
    axes.set_facecolor('white')  # 子图背景为白色

    cs = axes.contourf(x, y, rain, levels=np.array(bounds + [500]), cmap=cmap, norm=norm)

    clip_boundary(cs=cs, axes=axes, shape_file=shape_file)

    reader = Reader(shape_file)
    city = feature.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none')
    axes.add_feature(city, linewidth=0.3)  # 添加市界细节
    axes.set_extent(extent, crs=proj)

    # 显示经纬度
    gl = axes.gridlines(crs=crs.PlateCarree(), draw_labels=True, linewidth=0.5, color='g', alpha=0.5, linestyle='--')
    gl.top_labels = False  # 关闭顶端的经纬度标签
    gl.right_labels = False  # 关闭右侧的经纬度标签
    gl.xformatter = LONGITUDE_FORMATTER  # x轴设为经度的格式
    gl.yformatter = LATITUDE_FORMATTER  # y轴设为纬度的格式
    gl.xlocator = ticker.FixedLocator(np.arange(extent[0], extent[1] + 0.5, 0.3))
    gl.ylocator = ticker.FixedLocator(np.arange(extent[2], extent[3] + 0.5, 0.3))

    gl.xlabel_style = {'size': 10, 'family': 'Times New Roman', 'ha': 'center'}
    gl.ylabel_style = {'size': 10, 'family': 'Times New Roman', 'rotation': 90, 'va': 'center'}
    axes.set_title(title, fontsize=16)

    # plt.rcParams['axes.unicode_minus'] = False

    # plt.text(114.38, 38.30, s="灵寿", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')
    #
    # plt.text(114.55, 38.42, s="行唐", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 行唐
    #
    # plt.text(115.07, 38.01, s="晋州", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 晋州
    #
    # plt.text(114.57, 38.15, s="正定", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 正定
    #
    # plt.text(114.13, 38.03, s="井陉", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 井陉
    #
    # plt.text(114.22, 38.27, s="平山", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 平山
    #
    # plt.text(114.68, 38.35, s="新乐", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 新乐
    #
    # plt.text(114.83, 38.03, s="藁城", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 藁城
    #
    # plt.text(114.35, 38.06, s="鹿泉", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 鹿泉
    #
    # plt.text(114.95, 38.18, s="无极", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 无极
    #
    # plt.text(114.78, 37.75, s="赵县", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 赵县
    #
    # plt.text(114.63, 37.88, s="栾城", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 栾城
    #
    # plt.text(114.60, 37.63, s="高邑", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 高邑
    #
    # plt.text(114.50, 37.80, s="元氏", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 元氏
    #
    # plt.text(114.40, 37.65, s="赞皇", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 赞皇
    #
    # plt.text(115.18, 38.18, s="深泽", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 深泽
    #
    # plt.text(115.20, 37.93, s="辛集", color="red", weight="bold", style="italic", fontsize=5,
    #          verticalalignment='center', horizontalalignment='right')  # 辛集

    cb = fig.colorbar(cs, shrink=0.85, orientation='horizontal', extend='both', pad=0.1)
    cb.ax.tick_params(labelsize=6)
    plt.savefig(fname, format=format,transparent=True)

    plt.close('all')

